package cn.exrick.front.interceptor;

import cn.exrick.common.constant.CommonConstant;
import cn.exrick.manager.pojo.TbMember;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Component
public class LoginInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {

        //获取session
        HttpSession session = request.getSession();
        TbMember member = (TbMember) session.getAttribute(CommonConstant.USER_SESSION);
        if (member != null) {
            return true;
        }
        if("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))){
            //设置跳转地址
            response.setHeader("redirectUrl", "/login");
            //设置跳转使能
            response.setHeader("enableRedirect","true");
            response.flushBuffer();
        }else{
            response.sendRedirect("/login");
        }

        return false;
    }

    /**
     * 当前请求进行处理之后，也就是Controller方法调用之后执行，
     * 但是它会在DispatcherServlet 进行视图返回渲染之前被调用。
     * 此时我们可以通过modelAndView对模型数据进行处理或对视图进行处理。
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response,
                           Object handler, ModelAndView modelAndView) throws Exception {

    }

    /**
     * 方法将在整个请求结束之后，也就是在DispatcherServlet渲染了对应的视图之后执行。
     * 这个方法的主要作用是用于进行资源清理工作的。
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
                                Object handler, Exception ex) throws Exception {
    }
}
